//
//  LockManagerVC.m
//  AILock
//
//  Created by 谭亚明 on 2020/7/13.
//  Copyright © 2020 tym. All rights reserved.
//

#import "LockManagerVC.h"
#import "Sizes.h"
#import "WXApi.h"
#import "ShowAlertView.h"
#import "RepairDetailVC.h"
#import "FirmwareUpVC.h"
#import "NetWrokInfoVC.h"
#import "EquipmentService.h"
#import "BaseInfoVC.h"
#import "LockDeployVC.h"
#import "MessageHistoryVC.h"
#import "LockUsersVC.h"
#import "LockManagerCell.h"
@interface LockManagerVC ()<UICollectionViewDelegate,UICollectionViewDataSource>

@property(nonatomic,strong) UICollectionView *collectionView;
@property(nonatomic,weak) IBOutlet UIButton *deleteBtn;

@property(nonatomic,strong) EquipmentModel *equipModel;
@property(nonatomic,strong) NSArray *dataArray;

@property(nonatomic,strong) EquipmentService *services;
@end

@implementation LockManagerVC

-(instancetype)initWithEquipment:(EquipmentModel*)equipment{
    self = [super init];
    if (self) {
        self.equipModel = equipment;
    }
    return self;
}

-(EquipmentService*)services{
    if (_services == nil) {
        _services = [[EquipmentService alloc] init];
    }
    return _services;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self addBackBtnFunc];
    [self addTitle:@"门锁管理"];
    _dataArray = [[NSMutableArray alloc] initWithArray:@[
        @{@"title":@"用户管理",
          @"icon":@"icon_lockmanage1"
        },
        @{@"title":@"门锁配置",
          @"icon":@"icon_lockmanage2"},
        @{@"title":@"消息记录",
          @"icon":@"icon_lockmanage4"},
        @{@"title":@"基本信息",
          @"icon":@"icon_lockmanage3"},
        @{@"title":@"网络信息",
          @"icon":@"icon_lockmanage7"},
        @{@"title":@"固件升级",
          @"icon":@"icon_lockmanage5"},
        @{@"title":@"设备报修",
          @"icon":@"icon_lockmanage8"},
        @{@"title":@"同步用户",
          @"icon":@"icons"},
        @{@"title":@"时间校正",
          @"icon":@"icon_timeback"}]];
    
    [self.view addSubview:self.collectionView];
    
    if ([UserTool getCurrentFamily].familyRole == 2) {
        self.deleteBtn.hidden = YES;
    }
    self.deleteBtn.layer.masksToBounds= YES;
    self.deleteBtn.layer.cornerRadius = 5;
    self.deleteBtn.layer.borderColor = rgba(151, 151, 151).CGColor;
    self.deleteBtn.layer.borderWidth = 1;
}

- (UICollectionView *)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        CGFloat itemWidth = (ScreenWidth-30)/3;
        CGFloat itemHeight = 120;
        
        layout.itemSize = CGSizeMake(itemWidth, itemHeight);
        layout.sectionInset = UIEdgeInsetsZero;
        layout.minimumLineSpacing = 0;
        layout.minimumInteritemSpacing = 0;
        
        layout.scrollDirection = UICollectionViewScrollDirectionVertical;
        
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(15, 5, ScreenWidth - 30, ScreenHeight - NavigateonHeight - TabbarHeight - 44) collectionViewLayout:layout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.pagingEnabled = YES;
        _collectionView.backgroundColor = viewBGColor;
        [_collectionView registerNib:[UINib nibWithNibName:@"LockManagerCell" bundle:nil] forCellWithReuseIdentifier:[LockManagerCell identifier]];
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.scrollsToTop = NO;
        if (@available(iOS 11.0, *)) {
            _collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        } else {
            self.automaticallyAdjustsScrollViewInsets = NO;
        }
    }
    return _collectionView;
}

-(IBAction)deleteDeviceAction:(id)sender{
    [ShowAlertView showAlertViewTitle:@"提示" message:@"确定要从家庭中删除该设备吗？" actionBtnTitle:@"确定"
                           hiddenCancel:NO
                           completion:^(NSInteger actionType) {
        if (actionType) {
            [self deleteEquipmentServices];
        }
    }];
}

//删除设备的网络请求
-(void)deleteEquipmentServices{
    TYMWeak(self);
    [self.services getDeleteEquimpentWithID:self.equipModel.equipmentId completion:^(LMJBaseResponse * _Nonnull respons) {
        if (respons.message) {
            [WHToast showMessage:respons.message duration:2 finishHandler:nil];
        }else{
            [WHToast showMessage:@"删除成功" duration:2 finishHandler:^{
                [weakself.navigationController popToRootViewControllerAnimated:YES];
            }];
        }
    }];
}

#pragma mark -collectionview 数据源方法
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    
    return 1;   //返回section数
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _dataArray.count;
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    //创建item / 从缓存池中拿 Item
    LockManagerCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:[LockManagerCell identifier] forIndexPath:indexPath];
    NSDictionary *dic = _dataArray[indexPath.row];
    [cell.imageView setImage:[UIImage imageNamed:dic[@"icon"]]];
    cell.titleLab.text = dic[@"title"];
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row == 0) {
        LockUsersVC *lockVC = [[LockUsersVC alloc] initWithEquipment:self.equipModel];
        [self.navigationController pushViewController:lockVC animated:YES];
    }else if(indexPath.row == 1){
        LockDeployVC *deployVC = [[LockDeployVC alloc] initWithModel:self.equipModel];
        [self.navigationController pushViewController:deployVC animated:YES];
    }else if(indexPath.row == 2){
        MessageHistoryVC *messageVC = [[MessageHistoryVC alloc] initWithModel:self.equipModel];
        [self.navigationController pushViewController:messageVC animated:YES];
    }else if(indexPath.row == 3){
        BaseInfoVC *baseVC = [[BaseInfoVC alloc] initWithModel:self.equipModel];
        [self.navigationController pushViewController:baseVC animated:YES];
    }else if(indexPath.row == 4){
        NetWrokInfoVC *netw = [[NetWrokInfoVC alloc] initWithEquipmentModel:self.equipModel];
        [self.navigationController pushViewController:netw animated:YES];
    }else if(indexPath.row == 5){
        FirmwareUpVC *firVC = [[FirmwareUpVC alloc] initWithEquipmentModel:self.equipModel];
        [self.navigationController pushViewController:firVC animated:YES];
    }else if(indexPath.row == 6){
        
        if (![WXApi isWXAppInstalled]) {
            [WHToast showMessage:@"无法调用小程序" duration:2 finishHandler:nil];
            return;
        }
        
        WXLaunchMiniProgramReq *launchMiniProgramReq = [WXLaunchMiniProgramReq object];
        launchMiniProgramReq.userName = @"gh_0299e0221ca8";  //拉起的小程序的username
        launchMiniProgramReq.path = @"/pages/service/service";    ////拉起小程序页面的可带参路径，不填默认拉起小程序首页，对于小游戏，可以只传入 query 部分，来实现传参效果，如：传入 "?foo=bar"。
#ifdef DEBUG
    launchMiniProgramReq.miniProgramType = WXMiniProgramTypePreview; //拉起小程序的类型
#else
    launchMiniProgramReq.miniProgramType = WXMiniProgramTypeRelease; //拉起小程序的类型
#endif //拉起小程序的类型
        [WXApi sendReq:launchMiniProgramReq completion:^(BOOL success) {
           
        }];
        
//        RepairDetailVC *repairVC = [[RepairDetailVC alloc] initEquipMent:self.equipModel];
//        [self.navigationController pushViewController:repairVC animated:YES];
    }else if(indexPath.row == 7){
        [ShowAlertView showAlertViewTitle:@"提示" message:@"确定要同步用户吗?" actionBtnTitle:@"确定"
                               hiddenCancel:NO
                               completion:^(NSInteger actionType) {
            if (actionType) {
                [self getSynchronizeAppUser];
            }
        }];
        
    }else if(indexPath.row == 8){
        [ShowAlertView showAlertViewTitle:@"提示" message:@"确定要校正时间吗?" actionBtnTitle:@"确定"
                               hiddenCancel:NO
                               completion:^(NSInteger actionType) {
            if (actionType) {
                [self getEquipmentTiming];
            }
        }];
    }
}

//验证管理员
-(void)getVerifyAdminrole{
    TYMWeak(self);
    [self.services getVerifyadminroleEpumentId:self.equipModel.equipmentId completion:^(LMJBaseResponse * _Nonnull respons) {
        if (respons.code == 0) {
            [weakself getSynchronizeAppUser];
        }
    }];
}

-(void)getSynchronizeAppUser{
    TYMWeak(self);
    [self.services getEquipmentSynchronizeappuserEqipmentID:self.equipModel.equipmentId completion:^(LMJBaseResponse * _Nonnull respons, EquipmentModel * _Nonnull mdoel) {
        if (respons.code == 0){
            [WHToast showMessage:@"同步成功" duration:2 finishHandler:nil];
        }else{
            [ShowAlertView showAlertViewTitle:@"提示" message:respons.message actionBtnTitle:@"确定"
                                   hiddenCancel:NO
                                   completion:^(NSInteger actionType) {
                if(actionType){
                    if (respons.code == 2001) {
                        [weakself getVerifyAdminrole];
                    }
                }
            }];
        }
    }];
}

-(void)getEquipmentTiming{
    TYMWeak(self);
    [self.services getEquipmenttimingEqipmentID:self.equipModel.equipmentId completion:^(LMJBaseResponse * _Nonnull respons, EquipmentModel * _Nonnull mdoel) {
        if (respons.code == 0){
            [WHToast showMessage:@"校时成功" duration:2 finishHandler:nil];
        }else{
            [ShowAlertView showAlertViewTitle:@"提示" message:respons.message actionBtnTitle:@"确定"
                                   hiddenCancel:NO
                                   completion:^(NSInteger actionType) {
                if(actionType){
                    if (respons.code == 2001) {
                        [weakself getVerifyAdminrole];
                    }
                }
            }];
        }
    }];
}

@end
